package com.zib.vread.sinaweibo.mvp.view.fragment.login;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.zib.vread.sinaweibo.R;
import com.zib.vread.sinaweibo.api.AccessTokenKeeper;
import com.zib.vread.sinaweibo.api.Constants;
import com.zib.vread.sinaweibo.base.BaseFragment;
import com.zib.vread.sinaweibo.entity.Status;
import com.zib.vread.sinaweibo.entity.StatusList;
import com.zib.vread.sinaweibo.mvp.view.adapter.WeiboAdapter;
import com.zib.vread.sinaweibo.utils.DensityUtil;
import com.zib.vread.sinaweibo.utils.ScreenUtil;
import com.zib.vread.sinaweibo.widget.customview.GroupPopWindow;
import com.zib.vread.sinaweibo.widget.customview.IGroupItemClick;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by vread on 2016/8/3.
 */
public class LoginHomeFragment extends BaseFragment {
    @Bind(R.id.weiboRecyclerView)
    RecyclerView weiboRecyclerView;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.arrow)
    ImageView arrow;
    @Bind(R.id.getData)
    ImageView getData;
    @Bind(R.id.group)
    LinearLayout group;
    private Context mContext = getContext();
    private Handler handler = new Handler();
    private Oauth2AccessToken mAccessToken;
    private StatusesAPI mStatusesAPI;
    private ArrayList<Status> mDatas = new ArrayList<>();
    private WeiboAdapter mAdapter;
    private GroupPopWindow mPopWindow;
    private int page = 1;
    private long mCurrentGroup = Constants.GROUP_TYPE_ALL;

    public static LoginHomeFragment newInstance() {

        Bundle args = new Bundle();

        LoginHomeFragment fragment = new LoginHomeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_login_home;
    }

    @Override
    public void initView() {
        initexdata();
        initRecyclerView();
        initRefreshLayout();
    }

    public RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                if (response.startsWith("{\"statuses\"")) {
                    Log.i("TAG", "-----onComplete: " + response.toString());
                    StatusList statuses = StatusList.parse(response);
                    if (statuses != null && statuses.total_number > 0) {
                        mDatas.clear();
                        mDatas.addAll(statuses.statuses);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.notifyDataSetChanged();
                                swipeRefreshWidget.setRefreshing(false);
                            }
                        });
                    }
                } else if (response.startsWith("{\"created_at\"")) {
                } else {
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            ErrorInfo info = ErrorInfo.parse(e.getMessage());
        }
    };

    private void initexdata() {

        mAccessToken = AccessTokenKeeper.readAccessToken(getContext());

        mStatusesAPI = new StatusesAPI(getContext(), Constants.APP_KEY, mAccessToken);
        name.setText(mAccessToken.getUid());
        if (mAccessToken.isSessionValid()) {
            group.setVisibility(View.VISIBLE);
        }
        group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Rect rect = new Rect();
                getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                int statusBarHeight = rect.top;
                mPopWindow = GroupPopWindow.getInstance(getContext(), ScreenUtil.getScreenWidth(getContext()) * 3 / 5, ScreenUtil.getScreenHeight(getContext()) * 2 / 3);
                mPopWindow.showAtLocation(name, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, name.getHeight() + statusBarHeight + DensityUtil.dp2px(getContext(), 8));
                mPopWindow.setOnGroupItemClickListener(new IGroupItemClick() {
                    @Override
                    public void onGroupItemClick(int position, long groupId, String groupName) {
                        mCurrentGroup = groupId;
                        if (groupId != Constants.GROUP_TYPE_ALL) {
                            setGroupName(groupName);
                        } else {

                        }
                        mPopWindow.dismiss();

                        if (groupId == 0) {
                            mStatusesAPI.publicTimeline(50, page, false, mListener);
                            name.setText(mAccessToken.getUid());
                        } else if (groupId == 1) {
                            mStatusesAPI.friendsTimeline(0, 0, 50, 1, false, 0, false, mListener);
                        } else {
                            mStatusesAPI.mentions(0, 0, 50, 1, 0, 0, 0, false, mListener);
                        }

                    }
                });
                if (mPopWindow.isShowing()) {
                    mPopWindow.scrollToSelectIndex();
                }
            }
        });
    }

    public void initRecyclerView() {
        mAdapter = new WeiboAdapter(mDatas, context) {
            @Override
            public void arrowClick(Status status, int position) {

            }
        };
        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        weiboRecyclerView.setLayoutManager(layoutManager);
        weiboRecyclerView.setAdapter(mAdapter);
        mStatusesAPI.publicTimeline(50, page, false, mListener);
    }

    private void initRefreshLayout() {
        swipeRefreshWidget.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mStatusesAPI.publicTimeline(50, page, false, mListener);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void setGroupName(String userName) {
        name.setText(userName);
        if (group.getVisibility() != View.VISIBLE) {
            group.setVisibility(View.VISIBLE);
        }
    }
}
